<?php
    // Значения по умолчанию
    $article->data['ip'] = $user->ip;
    $article->data['ua'] = $user->ua;

    if ((!isset($_POST['add'])) && (!isset($_POST['editing_article_id']))) {
        // В первый раз зашли на страницу, 
        // просто создаём статью-черновик
        
        $article::db_query("INSERT INTO `".core::$table_name['articles']."`
        (`id`, `date`, `category`, `section`, `ip`, 
        `ua`, `author`, `title`, `description`, `article`, 
        `source`, `translation`, `views`, `comm_count`, 
        `url_name`, `tags`, `hidden`, `empty`, `to_comm`, `show_comm`) 
        VALUES
        (NULL, CURRENT_TIMESTAMP, '".$article->data['category']."', '".$article->data['section']."', '$user->ip', 
        '$user->ua', '$user->id', '".$article->data['title']."', 
        '".$article->data['description']."', '".$article->data['article']."', 
        '".$article->data['source']."', '0', '0', '0', 
        '".$article->data['url_name']."', '".$article->data['tags']."', '0', '1', '0', '1') --");
        $article->data['insert_id'] = $article::insert_id(); // Номер созданной записи
    } 
    if ((isset($_POST['editing_article_id'])) && (isset($_POST['add']))) {
        // Редактирование статьи
        // и не нужно создавать пустую запись в таблице articles

        $article->data['insert_id'] = abs((int)$_POST['editing_article_id']);
        $article->data['id'] = $article->data['insert_id'];
        $article->data['date'] = date('d.m.Y');
        $article->data['section'] = abs((int)$_POST['section']);
        $article->data['category'] = abs((int)$_POST['category']);
        $article->data['ip'] = $user->ip;
        $article->data['ua'] = $user->ua;
        $article->data['title'] = $_POST['title'];
        $article->data['url_name'] = $article->filter_lower_latin($article->getTranslited($_POST['title']));
        $article->data['description'] = $_POST['description'];
        $article->data['article'] = $_POST['article'];
        $article->data['source'] = $_POST['source'];
        $article->data['tags'] = $article->filter_lower_latin_space($_POST['tags']);

        $article::db_query("UPDATE `".core::$table_name['articles']."` SET 
        `date` = NOW(),
        `category` = '".$article->data['category']."',
        `section` = '".$article->data['section']."',
        `title` = '".$article->data['title']."',
        `description` = '".$article->data['description']."',
        `article` = '".$article->data['article']."',
        `source` = '".$article->data['source']."',
        `url_name` = '".$article->data['url_name']."',
        `tags` = '".$article->data['tags']."', 
        `hidden` = '0', `empty` = '0', `to_comm` = '1', `show_comm` = '1'
        WHERE `id` = ".$article->data['id']." -- ");

        $article_select = $article::db_query("SELECT * FROM `".core::$table_name['articles']."` WHERE `id` = ".$article->data['insert_id']." LIMIT 1 -- ");
        if (mysql_num_rows($article_select)) {
            $article->data['id'] = mysql_result($article_select, 0, 'id');
            $article->data['date'] = mysql_result($article_select, 0, 'date');
            $article->data['section'] = mysql_result($article_select, 0, 'id');
            $article->data['section_title'] = mysql_result($article_select, 0, 'id');
            $article->data['category'] = mysql_result($article_select, 0, 'id');
            $article->data['category_title'] = mysql_result($article_select, 0, 'id');
            $article->data['ip'] = $user->ip;
            $article->data['ua'] = $user->ua;
            $article->data['title'] = mysql_result($article_select, 0, 'title');
            $article->data['description'] = mysql_result($article_select, 0, 'description');
            $article->data['article'] = mysql_result($article_select, 0, 'article');
            $article->data['source'] = mysql_result($article_select, 0, 'source');
            $article->data['views'] = mysql_result($article_select, 0, 'views');
            $article->data['url_name'] = mysql_result($article_select, 0, 'url_name');
            $article->data['tags'] = mysql_result($article_select, 0, 'tags');
        }
    }
    
    // Загрузить список секций
    $section_select = $article::db_query("SELECT * FROM `articles_sections` -- ");
    $category_select = $article::db_query("SELECT * FROM `articles_categories` -- ");
?>

<form name="message" action="add_article" method="POST" enctype="multipart/form-data">
    <div class="add_col1">Заголовок</div>
    <div class="add_col2">
        <input type="text" class="add_title" name="title" maxlength="32" 
        placeholder="Заголовок статьи" value="<?php echo $article->data['title']; ?>" required>
    </div>
    <div class="add_col3">
    </div>

    <div class="clear"></div>

    <div class="add_col1">Секция</div>
        <div class="add_col2">
        <select size=1 name="section" class="add_cat" style="width: 256px;" onChange="load(value);">
            <?php
            while ($row = mysql_fetch_array($section_select)) {
                echo '<option name="section" value="'.$row['id'].'" selected>'.$row['full_title'].'</option>';
            }
            ?>
        </select>
    </div>


    <div class="clear"></div>

    <div class="add_col1">Категория</div>
    <div class="add_col2">
        <select size=1 id="xyu" name="category" class="add_cat" style="width: 256px;">
            <?php
            while ($row = mysql_fetch_array($category_select)) {
                echo '<option name="section" value="'.$row['id'].'" selected>'.$row['full_title'].'</option>';
            }
            ?>
        </select>
    </div>

  <details>
   <summary>Информация об авторе</summary>
   <p>Бендер Родригез</p>
  </details>

    <div class="clear"></div>

    <div class="add_col1">Источник</div>
    <div class="add_col2">
        <textarea class="add_description" name="source" maxlength="100" 
        placeholder="Источник информации (к примеру, адрес оригинала, если вы публикуете перевод). 
        Длина не более 100 символов."><?php echo $article->data['source']; ?></textarea>
    </div>

    <div class="clear"></div>
    
    <div class="add_col1">Описание</div>
    <div class="add_col2">
        <textarea class="add_description" name="description" maxlength="128" 
        placeholder="Краткое описание статьи (до 128 символов)" required><?php echo $article->data['description']; ?></textarea>
    </div>

    <div class="clear"></div>

    <div class="add_col1">&nbsp;</div>
    <div class="add_col2">
            <div name="description">
                <?php include('tags_bb.php'); ?>
            </div>
    </div>

    <div class="clear"></div>

    <div class="add_col1">&nbsp;</div>
    <div class="add_col2">
        <div name="description" class="toolpanel">
        <?php 
            for ($i=1;$i<=33;$i++) {
                echo '<a href="javascript:tag(\'[tool='.$i.']\', \'\')">
                <img src="/inc/php/html/themes/0/images/gimp_tools/'.$i.'.png" alt="url" title="'.$i.'"></a>';
            }
        ?>
        </div>
    </div>

    <div class="clear"></div>

    <div class="add_col1">Статья</div>
    <div class="add_col2">
        <textarea id="articlei" name="article" class="add_text" cols="13" 
        placeholder="Текст статьи" required><?php echo $article->data['article']; ?></textarea>
        <?php require('resize_textarea.php'); ?>
    </div>

    <div class="clear"></div>

    <div class="add_col1"></div>
    <div class="add_col2 articles_fm">
        <span>Прикреплённые изображения</span>
        <input type="file" name="images[]" class="add_images" style="width: 458px;" accept="image/jpeg" multiple>
        <input type="submit" name="add_2" class="add_images" style="width: 110px;" value="Прикрепить">
        <br><br>
        <?php
        /*
        // открываем папку
        $dh = opendir("data/articles/");
        while($filename = readdir($dh))
        {
            if (($filename == '.') || ($filename == '..')) {
                continue;
            }
            echo '
            <div class="articles_fm_thumbs">
                <a href="javascript:tag(\'\', \'[img='.$filename.']\')" title="img1">
                    <img src="/data/articles/'.$insert_id.'/'.$filename.'" class="articles_fm_image_thumb" alt="image">
                </a>
                <div class="articles_fm_buttons">
                    <div class="articles_fm_button"><a href="/add_article/">R</a></div>
                    <div class="articles_fm_button"><a href="/add_article/">X</a></div>
                </div>
            </div>';
        }*/
        ?>
    </div>

    <div class="clear"></div>

    <div class="add_col1">Теги</div>
    <div class="add_col2">
        <input type="text" class="add_title" name="tags" maxlength="128" placeholder="Ключевые слова через пробел" value="<?php echo $article->data['tags']; ?>">
    </div>

    <div class="clear"></div>

    <div class="add_col1">&nbsp;</div>
    <div class="add_col2">
        
        <?php
            if (isset($article->data['insert_id'])) {
                // Если только что создали статью
                echo '
                    <input type="hidden" name="editing_article_id" value="'.$article->data['insert_id'].'">
                ';
            }
        ?>
        
        <input type="submit" name="add" class="add_button" value="Опубликовать статью">
    </div>
</form>
<script>
    load(1);
</script>
